package com.pdemo.front.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pdemo.core.dao.AdminDao;
import com.pdemo.core.entity.SystemAdmin;
import com.pdemo.core.entity.SystemRole;
import com.pdemo.front.filter.ApplicationPrincipal;
import com.pdemo.front.filter.Token;

@Service("adminService")
public class AdminService {
	
	final static Logger logger = LogManager.getLogger(AdminService.class);
	
	@Autowired
	@Qualifier("passwordEncoder")
	PasswordEncoder passwordEncoder;
	
	@Autowired
	@Qualifier("adminDao")
	AdminDao adminDao;
	
	public ApplicationPrincipal authenticate(Token token){
		SystemAdmin admin = adminDao.getSystemAdminByMobile(token.getMobile());
		if(admin != null && admin.isEnabled() && passwordEncoder.matches(token.getToken(), admin.getPassword())){
			Set<String> roles = new HashSet<String>();
			for(SystemRole role : admin.getRoles()){
				roles.add(role.getRoleName());
			}
			logger.debug(admin.getMobile() + "Roles : "+ roles);
			return new ApplicationPrincipal(admin.getId(),Boolean.TRUE ,roles);
			
		}
		logger.warn("invalid username or password");
		return null;
	}
	
	@Transactional
	public Long createAdmin(SystemAdmin admin){
		admin.setPassword(passwordEncoder.encode(admin.getPassword()));
		adminDao.save(admin);
		return admin.getId();
	}
	
	
	public List<SystemAdmin> getAllSystemAdmin(){
		return adminDao.getAllSystemAdmin();
	}

}
